import * as Cesium from 'cesium';

export class BlinkingPointManager {
  private viewer: Cesium.Viewer | null;
  private currentBlinkingEntity: Cesium.Entity | null;
  private currentIntervalId: number | null;
  private handler: Cesium.ScreenSpaceEventHandler | null;

  constructor() {
    this.viewer = null;
    this.currentBlinkingEntity = null;
    this.currentIntervalId = null;
    this.handler = null;
  }

  // 切换闪烁状态
  toggleBlinking(entity: Cesium.Entity, viewer: Cesium.Viewer) {
    this.viewer = viewer;
    // 停止当前闪烁的点
    this.stopCurrentBlinking();

    // 开始新的闪烁
    this.startBlinking(entity);
  }

  // 停止当前闪烁的点
  stopCurrentBlinking() {
    if (this.currentBlinkingEntity) {
      // 恢复原始显示状态
      this.currentBlinkingEntity.show = true;

      // 清除定时器
      if (this.currentIntervalId) {
        clearInterval(this.currentIntervalId);
        this.currentIntervalId = null;
      }

      this.currentBlinkingEntity = null;
    }
  }

  // 开始闪烁指定实体
  startBlinking(entity: Cesium.Entity) {
    this.currentBlinkingEntity = entity;
    let show = true;
    const blinkInterval = 1000; // 闪烁间隔(毫秒)

    // 设置闪烁定时器
    this.currentIntervalId = setInterval(() => {
      show = !show;
      if (entity) {
        entity.show = show;
      }
    }, blinkInterval) as any; // 或使用 window.setInterval 若存在冲突
  }

  // 销毁清理
  destroy() {
    this.stopCurrentBlinking();
    if (this.handler) {
      this.handler.destroy();
      this.handler = null;
    }
  }
}
